﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace SCG.WinForms
{
    public partial class ThreadTimer : Component
    {
        //constructors
        public ThreadTimer()
        {
            Priority = ThreadPriority.Normal;
            Interval = 1000;
            InitializeComponent();
        }
        public ThreadTimer(IContainer container)
        {
            container.Add(this);
            Priority = ThreadPriority.Normal;
            Interval = 1000;
            InitializeComponent();
        }

        //events
        public event EventHandler<EventArgs> Tick;

        //public properties
        public ThreadPriority Priority { get; set; }
        public int Interval { get; set; }

        //running?
        public bool IsRunning
        {
            get
            {
                return _thread != null;
            }
        }

        //control
        public void Start()
        {
            if (_thread != null)
                return;
            _thread = new Thread(new ThreadStart(RunThread));
            _thread.IsBackground = true;
            _thread.Priority = Priority;
            _thread.Start();
        }
        public void Stop()
        {
            _kill = true;
            _thread = null;
        }

        //private members
        private Thread _thread = null;
        private bool _kill = false;

        //thread method
        private void RunThread()
        {
            while (!_kill)
            {
                if (Tick != null)
                    Tick(this, EventArgs.Empty);
                Thread.Sleep(Interval);
            }
        }
    }
}
